package com.woniu.core.service.Impl;

import com.woniu.core.entity.CoreMenus;
import com.woniu.core.mapper.CoreMenusMapper;
import com.woniu.core.service.CoreMenusService;
import com.woniu.util.utils.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CoreMenusServiceImpl implements CoreMenusService {
    @Autowired
    private CoreMenusMapper coreMenusMapper;

    @Override
    public HttpResult<?> queryCoreMenusByAccount(String account) {
        List<CoreMenus> coreMenus = coreMenusMapper.queryCoreMenusByAccount(account);
        for (CoreMenus coreMenu : coreMenus) {
            System.out.println(coreMenu);
        }
        List<CoreMenus> menuNode = getMenuNode(coreMenus);
        return new HttpResult<>().ok(menuNode);
    }


    //把菜单封装成树形结构
    public List<CoreMenus> getMenuNode(List<CoreMenus> menus) {
        List<CoreMenus> parentMenus = menus.stream().filter(e -> e.getMenuParentId() == null)
                .collect(Collectors.toList());
        for (CoreMenus parentMenu : parentMenus) {
            List<CoreMenus> childrenMenus = new ArrayList<>();
            for (CoreMenus menu : menus) {
                //找出一级菜单对应二级菜单
                if (parentMenu.getMenuId().equals(menu.getMenuParentId())) {
                    childrenMenus.add(menu);
                }
            }
            parentMenu.setChildrenMenu(childrenMenus);
        }
        return parentMenus;
    }
}
